<template>
  <div class="tree">
    <div class="treeContent">
      <el-row>
        <el-col :span="24">
          <el-input
            v-model="filterText"
            size="mini"
            placeholder="关键字搜索"
            suffix-icon="iconfont icon-wenjianjia"
          />
        </el-col>
      </el-row>
      <!-- default-expand-all 默认展开所有节点 -->
      <!-- highlight-current 高亮当前选中节点 -->
      <!-- auto-expand-parent 展开子节点的时候自动展开父节点 -->
      <el-scrollbar style="height: 100%">
        <el-tree
          ref="tree"
          icon-class="iconfont icon-wenjianjia"
          node-key="id"
          highlight-current
          auto-expand-parent
          :data="treeData"
          :default-expand-all="false"
          :filter-node-method="filterNode"
          :default-expanded-keys="defaultExpandedKeys"
          @node-click="treeNodeClick"
        />
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Tree',
  props: {
    selectedNode: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      filterText: '', // 搜索节点关键字
      defaultExpandedKeys: [],
      treeData: [
        {
          id: 1,
          label: '一级 id:1',
          children: [
            {
              id: 3,
              label: '二级 id:3',
              children: [
                {
                  id: 4,
                  label: '三级 id:4'
                }
              ]
            }
          ]
        },
        {
          id: 2,
          label: '一级 id:2'
        }
      ]
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    selectedNode: {
      handler(newVal, oldVal) {
        if (newVal && Object.keys(newVal).length !== 0) {
          console.log('行点击选中的节点数据：', JSON.stringify(newVal))
          // 亮尚节点
          this.$refs.tree.setCurrentKey(newVal.treeId)
          // 展开节点
          this.defaultExpandedKeys = [newVal.treeId]
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {},
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    treeNodeClick(row, node, e) {
      // 判断是否存在子节点，存在则取消传递数据，不存在则传递数据，如不需要该判断则去掉
      if (!row.children || row.children.length === 0) {
        this.$emit('treeNodeClick', row)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/tree.scss';
</style>
